package com.laicunba.service.accounting.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.laicunba.pojo.FinancingTargetBidDO;
import com.laicunba.pojo.UserBankDO;
import com.laicunba.pojo.UserDO;
import com.laicunba.service.FinancingTargetBidService;
import com.laicunba.service.FinancingTargetService;
import com.laicunba.service.SaleService;
import com.laicunba.service.UserBankService;
import com.laicunba.service.UserService;
import com.laicunba.service.accounting.AccountingTemplate;
import com.laicunba.service.accounting.FuiouBuyService;
import com.laicunba.service.exception.DangerBidException;
import com.laicunba.util.AssertUtil;
import com.laicunba.util.StringUtil;

public class FuiouBuyServiceImpl extends AccountingTemplate implements FuiouBuyService {
	@Autowired
	private SaleService saleService;
	@Autowired
	private UserService userService;
	@Autowired
	private FinancingTargetService financingTargetService;

	@Autowired
	private FinancingTargetBidService financingTargetBidService;
	@Autowired
	private UserBankService userBankService;

	@Transactional
	@Override
	public boolean doPaySuccess(DoPaySuccessParam param) {
		List<FinancingTargetBidDO> bidList = financingTargetBidService.findByCertificateId(param.getCertificateId());
		AssertUtil.assertTrue(bidList != null && !bidList.isEmpty(), "CANT_FIND_BID");
		AssertUtil.assertTrue(bidList.size() == 1, "FIND_MANY_BID");

		UserDO user = userService.get(UserDO.class, bidList.get(0).getBidUserId());
		AssertUtil.assertNotNull(user, "USER_NOT_EXIST");
		if (StringUtil.isNotEmpty(user.getPid())) {
			// 异名卡,抛危险交易
			AssertUtil.assertTrue(user.getPid().equals(bidList.get(0).getPayPid()), new DangerBidException(DangerBidException.CODE_DENY_CARD, bidList.get(0).getId()));

			// 未事先绑定的,同名卡,抛危险交易
			UserBankDO existBankCard = userBankService.find(user.getId(), bidList.get(0).getBankCardNo());
			if (existBankCard == null) {
				if(!userBankService.testNewCardPolicy(user.getId(), bidList.get(0).getBankCardNo())){
					List list = userBankService.findByUserId(user.getId());
					AssertUtil.assertTrue(list == null || list.isEmpty(), new DangerBidException(DangerBidException.CODE_DENY_CARD, bidList.get(0).getId()));
				}
			}
		}

		SaleService.PayedFinancingTargetParam payedFinancingTargetParam = new SaleService.PayedFinancingTargetParam();
		payedFinancingTargetParam.setCertificateId(param.getCertificateId());
		payedFinancingTargetParam.setPayMark(param.getPayMark());
		AssertUtil.assertTrue(saleService.payedFinancingTarget(payedFinancingTargetParam), "PAYED_FINANCING_TARGET_ERROR");

		return true;
	}

}
